from functools import wraps
from flask import request, jsonify
from flask_jwt_extended import get_jwt_identity
from app.models.user import User
from app.models.operation_log import OperationLog
from app import db

def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user_id = get_jwt_identity()
        user = User.query.get(user_id)
        if not user or user.role != 'admin':
            return jsonify({'error': '需要管理员权限'}), 403
        return f(*args, **kwargs)
    return decorated_function

def log_operation(operation_type):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            response = f(*args, **kwargs)
            
            # 记录操作日志
            try:
                user_id = get_jwt_identity()
                log = OperationLog(
                    user_id=user_id,
                    operation_type=operation_type,
                    operation_detail=str(request.get_json()),
                    ip_address=request.remote_addr
                )
                db.session.add(log)
                db.session.commit()
            except Exception as e:
                print(f"记录日志失败: {str(e)}")
                
            return response
        return decorated_function
    return decorator 